<template>
  <div>
    <div class="content">
      <span>我的频道</span>
      <van-button @click="isshow = !isshow" type="danger" plain size="small">{{
        isshow ? '取消' : '编辑'
      }}</van-button>
    </div>
    <van-grid>
      <van-grid-item v-for="(item, index) in ownChannels" :key="item.id">
        <template>
          <van-icon
            class="chacha"
            name="cross"
            v-show="isshow && item.name !== '推荐'"
            @click="send(index)"
          />
          <span @click="changeActive(index)" :class="{ active: index == vv }">{{
            item.name
          }}</span>
        </template>
      </van-grid-item>
    </van-grid>
    <!-- 下面的可选频道 -->
    <div class="kexuan">可选频道</div>
    <van-grid>
      <van-grid-item
        v-for="(item, index) in optChannels"
        :key="item.id"
        :text="item.name"
        @click="addto(item, index)"
      />
    </van-grid>
  </div>
</template>

<script>
import { allChannelApi, addApi } from '@/Api'

export default {
  model: {
    prop: 'vv',
    event: 'chch'
  },
  props: {
    ownChannels: {
      type: Array,
      required: true
    },
    vv: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      allChannels: [],
      isshow: false
    }
  },
  methods: {
    addto (item) {
      // 先把当前选中的频道追加进我的频道
      this.ownChannels.push(item)
      //
      this.save()
    },

    send (index) {
      this.ownChannels.splice(index, 1)
      this.save()
      if(index<this.vv){
        this.$emit('fix')
      }
    },
    changeActive (index) {
      this.$emit('chch', index)
      this.$emit('close')
    },
    // 封装的存储频道的防范,判断登录了就发请求,没登录的话就保存到本地
    async save () {
      const channels = this.ownChannels.map((v, i) => {
        return {
          id: v.id,
          seq: i
        }
      })
      // 判断是否登录
      if (this.$store.state.tokenobj.token) {
        await addApi({ channels })
        // console.log('返回值', res)
      } else {
        // 如果没有登录就保存到本地存储中而且要转成json格式
        window.localStorage.setItem(
          'HMTT81_CHANNELS',
          JSON.stringify(this.ownChannels)
        )
      }
    }
  },
  computed: {
    optChannels () {
      return this.allChannels.filter(v => {
        return !this.ownChannels.find(f => v.id == f.id)
      })
    }
  },
  async created () {
    console.log('hah a')
    let res = await allChannelApi()
    // console.log(res)
    this.allChannels = res.data.data.channels
  }
}
</script>

<style lang="less" scoped>
.content {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  font-size: 14px;
}
.van-grid {
  margin-bottom: 10px;
  span {
    font-size: 14px;
  }
  .chacha {
    position: absolute;
    right: 2px;
    top: 2px;
  }
}
.active {
  color: red;
}
</style>
